<?php
class NewsAction extends MbaseAction {
	public $tbname = 'News';
	public $obj = '';
	public $mpk = 'news_id';
	public function _initialize() {
		parent :: _initialize();
		$this->assign('ncates', $this->getCateTree());

	}
	public function create() {
		if ($this->isPost()) {
			$data = $this->obj->getForm();
			//dump($data);
			$rs = $this->obj->doPost($data);
			if (!$rs) {
				$this->error($this->obj->getError());
				return false;
			} else {
				$tags = isset($_POST['keywords'])? $_POST['keywords']:0;
				$nmap['name'] = $data['name'];
				$news_id = $this->obj->where($nmap)->order('news_id desc')->getField('news_id');
				if($tags){
					$tarr = explode(',',$tags);
					$mtag = M('Tag');
					$mnt = M('News_tag');
					$ntarr = array();
					foreach($tarr as $vo){
						$map['tag'] = $vo;
						$isext = $mtag->where($map)->getField('tag_id');
						if(!$isext) $isext = $mtag->add(array('tag'=>$vo));
						$ntarr[] = array(
							'id' => '',
							'tag_id' => $isext,
							'news_id' => $news_id
						);
					}
					$mnt->addAll($ntarr);
				}
				$this->setClose('dialog', MODULE_NAME . '_create');
				$this->setReload('navtab', MODULE_NAME . '_index');
				$this->success('创建成功');
			}
		} else {
			$this->display();
		}

	}

	public function update() {
		if ($this->isPost()) {
			Vendor('Soa.SoaApi');
			$data = $this->obj->getForm(2);
			//echo json_encode($data);
			$rs = $this->obj->doPut($data);
			$news_id = $data['news_id'];
			$tags = isset($_POST['keywords'])? $_POST['keywords']:0;
			if($tags){
				$tarr = explode(',',$tags);
				$mtag = M('Tag');
				$mnt = M('News_tag');
				$ntarr = array();
				$ntmap['news_id'] = $news_id;
				$mnt->where($ntmap)->delete();
				foreach($tarr as $vo){
					$map['tag'] = $vo;
					$isext = $mtag->where($map)->getField('tag_id');
					if(!$isext) $isext = $mtag->add(array('tag'=>$vo));
					$ntarr[] = array(
						'id' => '',
						'tag_id' => $isext,
						'news_id' => $news_id
					);
				}
				$mnt->addAll($ntarr);
			}
			$this->setClose('dialog', MODULE_NAME . '_edit');
			$this->setReload('navtab', MODULE_NAME . '_index');
			$this->success('修改成功');
			if (!$rs) {
				$this->error($this->obj->getError());
				return false;
			} else {
				$this->setClose('dialog', MODULE_NAME . '_edit');
				$this->setReload('navtab', MODULE_NAME . '_index');
				$this->success($this->obj->getError());
			}
		}
	}
	public function getCateTree($reset = 0) {
		$tcateher = array ();
		if (S('ncates') && $reset == 0) {
			$tcateher = S('ncates');
		} else {
			$mcate = D('News_cate');
			$tcateher = $mcate->doGet();
			S('ncates', $tcateher);
		}
		return $tcateher;
	}
}
?>